package com.duanjw.springboot.es.service.impl;

import java.awt.print.Book;
import java.util.List;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import com.duanjw.springboot.es.JobRepository;
import com.duanjw.springboot.es.pojo.entity.Job;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class JobServiceImpl implements JobService {

    private final JobRepository jobRepository;
    private final ElasticsearchOperations operations;

    @Override
    public String saveJob(Job job) {
        return jobRepository.save(job).getId();
    }


    @Override
    public List<Job> searchJob(Integer pageNumber, Integer pageSize, String searchContent) {
        // 短语匹配到的搜索词，求和模式累加权重分
        // 权重分查询 https://www.elastic.co/guide/cn/elasticsearch/guide/current/function-score-query.html
        //   - 短语匹配 https://www.elastic.co/guide/cn/elasticsearch/guide/current/phrase-matching.html
        //   - 字段对应权重分设置，可以优化成 enum
        //   - 由于无相关性的分值默认为 1 ，设置权重分最小值为 10
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(new FunctionScoreQueryBuilder.FilterFunctionBuilder[] {
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("name", searchContent),
                        ScoreFunctionBuilders.weightFactorFunction(1000)),
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("description", searchContent),
                        ScoreFunctionBuilders.weightFactorFunction(500)) });

        // 分页参数
        Pageable pageable = PageRequest.of(pageNumber, pageSize);
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withPageable(pageable)
                .withQuery(functionScoreQueryBuilder).build();
        List<Job> sampleEntities = operations.multiGet(nativeSearchQuery, Job.class, IndexCoordinates.of("job"));
        return sampleEntities;
    }

    @Override
    public Iterable<Job> listJob() {
        Iterable<Job> all = jobRepository.findAll();
        return all;
    }

    @Override
    public Job findById(String id) {
        return jobRepository.findById(id).orElse(null);
    }
}
